package org.dandsoft.blackbox.snn.util.automaton;

/**
 * Created by IntelliJ IDEA.
 * User: dvilyuzhanin
 * Date: 08.04.2009 11:27:24
 */
public class DefaultLoopConnection extends AbstractLoopConnection<DefaultState> {
    private String counterVariable;

    public DefaultLoopConnection(String counterVariable) {
        this(counterVariable, 0);
    }

    public DefaultLoopConnection(String counterVariable, int repeatCount) {
        super(repeatCount);
        this.counterVariable = counterVariable;
    }

    protected int getCounter(DefaultState state) {
        Integer counter;
        try {
            counter = (Integer) state.getVariables().get(counterVariable);
        } catch (ClassCastException e) {
            throw new ClassCastException("Counter variable must be java.lang.Integer: var=" + counterVariable +
                    ", instead=" + e.getClass());
        }
        if (counter != null) {
            return counter;
        } else {
            throw new NullPointerException("Counter variable is null: " + counterVariable);
        }
    }

    protected void incrementCounter(DefaultState state) {
        Integer counter;
        try {
            counter = (Integer) state.getVariables().get(counterVariable);
        } catch (ClassCastException e) {
            throw new ClassCastException("Counter variable must be java.lang.Integer: var=" + counterVariable +
                    ", instead=" + e.getClass());
        }
        state.getVariables().put(counterVariable, counter + 1);
    }
}
